package com.dtsz.m2.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.dtsz.m2.R;
import com.dtsz.m2.ui.base.BaseActivity;
import com.dtsz.m2.utils.QrcodeUtils;
import com.dtsz.m2.volley.state.HUCState;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 推广二维码
 */

public class QrcodeActivity extends BaseActivity {
    private ImageView ivQrcode;
    private String urlCode, urlCodeNumber;
    private TextView tvCodeNumber;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_qrcode);
        super.onCreate(savedInstanceState);
        tvActionbarTitle.setText("邀请好友");
        tvCodeNumber.setText(urlCodeNumber);
    }

    @Override
    public void initUtils() {
        super.initUtils();
        Intent intent = getIntent();
        urlCode = "https://www.m2.app";
        urlCodeNumber = intent.getStringExtra("URLCode");

    }

    @Override
    public void initClick() {
        super.initClick();
//        findViewById(R.id.tv_save).setOnClickListener(this);
        findViewById(R.id.tv_code).setOnClickListener(this);
        ivQrcode.setOnClickListener(this);
    }

    @Override
    public void initView() {
        super.initView();
        ivQrcode = findViewById(R.id.iv_qrcode);
        tvCodeNumber = findViewById(R.id.tv_code_number);
        //  ivQrcode.setImageBitmap(QrcodeUtils.createQRImage(urlCode, 720, 720));
        Bitmap bitmap = QrcodeUtils.createQRCode(urlCode, 720, 720,
                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

        ivQrcode.setImageBitmap(bitmap);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_code:
                copy(this, urlCode);
                break;
            case R.id.tv_save:
                if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) ||
                        !(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
                    //没有权限，申请权限
                    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
                    //申请权限，其中RC_PERMISSION是权限申请码，用来标志权限申请的
                    ActivityCompat.requestPermissions(this, permissions, HUCState.HUC_REQEUST_CODE_1);

                } else {
                    //跳转到调用系统相机
                    saveImageView(getViewBitmap(ivQrcode));
                }

                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == HUCState.HUC_REQEUST_CODE_1) {
            if (grantResults.length == 2
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                saveImageView(getViewBitmap(ivQrcode));
            }
        } else {
            showToast("获取内存权限失败，保存二维码失败！");
        }
    }

    //系统剪贴板-复制:   s为内容
    public void copy(Context context, String s) {
        // 获取系统剪贴板
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
        ClipData clipData = ClipData.newPlainText(null, s);
        // 把数据集设置（复制）到剪贴板
        clipboard.setPrimaryClip(clipData);
        showToast("复制成功");

    }

    private class SaveSubscriber extends Subscriber<String> {

        @Override
        public void onCompleted() {
            Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(Throwable e) {
            Log.i(getClass().getSimpleName(), e.toString());
            Toast.makeText(getApplicationContext(), "保存失败——> " + e.toString(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNext(String s) {
            Toast.makeText(getApplicationContext(), "保存路径为：-->  " + s, Toast.LENGTH_SHORT).show();
        }
    }


    private class SaveObservable implements Observable.OnSubscribe<String> {

        private Bitmap drawingCache = null;

        public SaveObservable(Bitmap drawingCache) {
            this.drawingCache = drawingCache;
        }

        @Override
        public void call(Subscriber<? super String> subscriber) {
            if (drawingCache == null) {
                subscriber.onError(new NullPointerException("imageview的bitmap获取为null,请确认imageview显示图片了"));
            } else {
                try {
                    //File imageFile = new File(Environment.getExternalStorageDirectory(), "saveImageview.jpg");
                    ContextWrapper cw = new ContextWrapper(QrcodeActivity.this);
                    File directory = cw.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                    File imageFile = new File(directory, "m2.jpg");
                    FileOutputStream outStream = new FileOutputStream(imageFile);
                    drawingCache.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    subscriber.onNext(imageFile.getPath());
                    subscriber.onCompleted();
                    outStream.flush();
                    outStream.close();
                    // 其次把文件插入到系统图库
                    String path = imageFile.getAbsolutePath();
                    try {
                        MediaStore.Images.Media.insertImage(QrcodeActivity.this.getContentResolver(), path, "m2.jpg", null);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    // 最后通知图库更新
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(imageFile);
                    intent.setData(uri);
                    QrcodeActivity.this.sendBroadcast(intent);
                } catch (IOException e) {
                    subscriber.onError(e);
                }
            }
        }
    }

    private void saveImageView(Bitmap drawingCache) {
        Observable.create(new SaveObservable(drawingCache))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SaveSubscriber());
    }

    /**
     * 某些机型直接获取会为null,在这里处理一下防止国内某些机型返回null
     */
    private Bitmap getViewBitmap(View view) {
        if (view == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }
}
